package com.yk.neon.lib.util.mybatis.converter;

import com.yk.neon.lib.util.mybatis.constant.EnumType;
import com.yk.neon.lib.util.result.exception.BuzException;
import org.dozer.CustomConverter;

import java.lang.reflect.Method;
import java.util.Objects;

public class Enum2IntegerConverter implements CustomConverter {
	@Override
	public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) {
		if (Objects.isNull(source)) {
			return null;
		}
		if (source instanceof EnumType) {
			return ((EnumType) source).value();
		} else if (source instanceof Integer) {
			return getEnum(destinationClass, source);
		}
		return null;
	}

	private Object getEnum(Class<?> destinationClass, Object source) {
		try {
			Method m = destinationClass.getDeclaredMethod("getEnum", Integer.class);
			return m.invoke(destinationClass, (Integer) source);
		} catch (Exception e) {
			throw new BuzException("Enum not provide static getEnum(Integer value) method");
		}
	}
}
